package handlers

import (
	"data_service/models"
	"data_service/server"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// 初始化公告业务服务
var noticeService = server.NewNoticeService()

// GetLatestNotice 获取最新公告
func GetLatestNotice(c *gin.Context) {
	notice, err := noticeService.GetLatestNotice()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{})
		return
	}
	c.JSON(http.StatusOK, notice)
}

// CreateNotice 创建新公告
func CreateNotice(c *gin.Context) {
	var notice models.Notice
	if err := c.ShouldBindJSON(&notice); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的参数"})
		return
	}
	notice.CreatedAt = time.Now()
	if err := noticeService.CreateNotice(&notice); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建公告失败"})
		return
	}
	c.JSON(http.StatusOK, notice)
}

// GetAllNoticesAdmin 获取所有公告列表
func GetAllNoticesAdmin(c *gin.Context) {
	notices, err := noticeService.GetAllNotices()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取公告列表失败"})
		return
	}
	c.JSON(http.StatusOK, notices)
}

// DeleteNoticeAdmin 删除公告
func DeleteNoticeAdmin(c *gin.Context) {
	noticeId := c.Param("id")
	if err := noticeService.DeleteNotice(noticeId); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除公告失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "公告删除成功"})
}
